#include "http.hpp"


std::string RequestToStr(const HttpRequest &req)
{
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (auto &it : req._params)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }

    for (auto &it : req._headers)
    {
        ss << it.first << ": " << it.second << "\r\n";
    }

    ss << "\r\n";
    ss << req._body;
    return ss.str();
}

void Hello(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetContent(RequestToStr(req), "text/plain");
    
    //sleep(15); //测试client4 
}
void Login(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetContent(RequestToStr(req), "text/plain");
}
void PutFile(const HttpRequest &req, HttpResponse *rsp)
{
    std::string pathname = "./wwwroot" + req._path;
    Util::WriteFile(pathname, req._body);
}
void DelFile(const HttpRequest &req, HttpResponse *rsp)
{
    rsp->SetContent(RequestToStr(req), "text/plain");
}

int main()
{
    //Log::setDefaultLoggerLevel(Log::LogLevel::value::ERROR);
    HttpServer server(8080);
    server.SetThreadCount(2);
    server.SetBaseDir("./wwwroot");
    //这里的 Hello 是一个函数指针，它在传参时会转换成一个 右值（临时对象）
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.Start();
    return 0;
}
